package com.heliang.util;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.heliang.service.BaseService;

public class NetDataLoader {
	private static final String TAG="NetAccessUtil";

	private BlockingQueue<Runnable> queue ;   
	public static ThreadPoolExecutor executor ;
	  
	     public NetDataLoader() {
	    	 // 线程池：最大50条，每次执行：1条，空闲线程结束的超时时间：180秒
	    	 queue = new LinkedBlockingQueue<Runnable>();
	    	 executor = new ThreadPoolExecutor(2, 50, 180, TimeUnit.SECONDS, queue);
	     }
	  
	     /**
	      *  访问服务器接口
	      * @param baseService
	      * @param dataCallback
	      * @param type 0:updateData 1:getMore 
	      */
	     public void loadData(final BaseService baseService,final DataCallback dataCallback,final int type) {
	         final Handler handler = new Handler() {
	             public void handleMessage(Message message) {
	            	 dataCallback.dataLoaded((BaseService) message.obj);
	             }
	         };
	         
	         // 用线程池来做下载图片的任务
	         executor.execute(new Runnable() {
	             @Override
	             public void run() {
	            	try {
	            		switch (type) {
						case 0:
							baseService.updateData();
							break;
						case 1:
							baseService.getMoreData();
							break;
						case 2:
							break;
						default:
							break;
						}
	            		
	            		Message message = handler.obtainMessage(0, baseService);
	            		handler.sendMessage(message);
					} catch (Exception e) {
						// TODO: handle exception
					   e.printStackTrace();
						Log.e("net", e.getMessage());
					}
	                 
	             }
	         });
	     }
	  
//	     public void loadData(final String url,final DataCallback dataCallback){
//	    	 final Handler handler = new Handler() {
//	             public void handleMessage(Message message) {
//	            	 dataCallback.dataLoaded((BaseService) message.obj);
//	             }
//	         };
//	         
//	         // 用线程池来做下载图片的任务
//	         executor.execute(new Runnable() {
//	             @Override
//	             public void run() {
//	            	try {
//	            		RspBodyBaseBean rspBodyBaseBean = ProtocolBL.dataProcess(reqBodyBaseBean, url, cmdType)
//	            		Message message = handler.obtainMessage(0, baseSevice);
//	            		handler.sendMessage(message);
//					} catch (Exception e) {
//						// TODO: handle exception
//						Log.e(Constants.TAG, e.getMessage());
//					}
//	                 
//	             }
//	         });
//	     }
	     
	     public interface DataCallback {
	         public void dataLoaded(BaseService baseService);
	     }

}
